<template>
  <div>
    <el-drawer title="课程详情" :visible.sync="addOrUpdateVisible" :with-header="false" size="650px">
      <div class="right-container">
        <div class="container-header">
          <div style="font-size: 14px">订单查看</div>
          <div @click="handleClose">
            <i class="el-icon-close" style="font-size: 18px"></i>
          </div>
        </div>
        <div class="container-content background-color-grey padding-10">
          <div class="bg-white border-radius">
            <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title ">
              <div>
                <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                订单信息
              </div>
            </div>
            <div class="padding-lg flex ">
              <div class="flex-1">订单编号：{{classOrder.channelOrderNo}}</div>
            </div>
            <div class="padding-lg flex ">
              <div class="flex-1">订单状态：{{transformPaymentStatus(classOrder.paymentStatus,classOrder.returnTime)}}</div>
            </div>
            <div class="padding-lg flex ">
              <div class="flex-1">客户信息：{{classOrder.userName}},{{classOrder.userPhone}}</div>
            </div>
            <div class="padding-lg flex ">
              <div class="flex-1">订单总额：{{classOrder.orderAmount}}</div>
            </div>
          </div>
          <div class="div-jiange"></div>
          <div class="bg-white border-redius margin-top-md">
            <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
              <div>
                <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                支付记录
              </div>
            </div>
            <div class="padding-lr-lg padding-bottom-lg">
              <el-table :header-cell-style="tableHeaderStyle" :data="commentList" border
                        v-loading="false" style="width: 100%;">
                <el-table-column prop="id" label="序号" width="60" align="center">
                  <template slot-scope="scope">
                    <span>{{scope.row.xuhao}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="paymentTime" label="支付时间" width="100" align="center"
                                 header-align="left"></el-table-column>
                <el-table-column prop="orderAmount" label="支付金额" width="100" align="center"
                                 header-align="center"></el-table-column>
                <el-table-column prop="paymentStatus" label="支付状态" width="100" align="center" header-align="center">
                  <template slot-scope="scope">
                    <span>{{ transformPaymentStatus(scope.row.paymentStatus,scope.row.returnTime) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="paymentType" label="支付方式" width="100" align="center" header-align="center">
                  <template slot-scope="scope">
                    <span>{{ transformPay(scope.row.paymentType) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="channelOrderNo" label="支付流水" align="center" header-align="center"></el-table-column>
              </el-table>

              <!--                <el-pagination @size-change="sizeChangeHandleComment" @current-change="currentChangeHandleComment"-->
              <!--                               :current-page="pageIndexComment" :page-sizes="[10, 20, 50, 100]" :page-size="pageSizeComment" :total="totalPageComment"-->
              <!--                               layout="total, sizes, prev, pager, next, jumper">-->
              <!--                </el-pagination>-->
            </div>
          </div>
          <div class="div-jiange"></div>
          <div class="bg-white border-radius margin-top-md">
            <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title">
              <div>
                <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                产品信息
              </div>
            </div>
            <div class="padding-lr-lg padding-bottom-lg">

              <el-table :header-cell-style="tableHeaderStyle" :data="classOrder.classOrderItemList" border
                        v-loading="false" style="width: 100%;">
                <el-table-column prop="id" label="序号" width="60" align="center">
                  <template slot-scope="scope">
                    <span>{{scope.row.xuhao}}</span>
                  </template>
                </el-table-column>

                <el-table-column prop="manageName" header-align="left" align="left" label="产品">
                </el-table-column>

                <el-table-column prop="price" header-align="center" align="center" label="单价" width="100">
                </el-table-column>

                <el-table-column prop="number" header-align="center" align="center" label="数量" width="100">
                  <!--                    <template slot-scope="scope">-->
                  <!--                      <span v-if="scope.row.score&&scope.row.score<=0">未考试</span>-->
                  <!--                      <span v-else-if="scope.row.status === 1" >已通过&nbsp;&nbsp;考试得分：{{scope.row.score}} / 100</span>-->
                  <!--                      <span v-else>未通过&nbsp;&nbsp;考试得分：{{scope.row.score}} / 100</span>-->
                  <!--                    </template>-->
                </el-table-column>
              </el-table>
              <!--                <el-pagination @size-change="sizeChangeHandleExam" @current-change="currentChangeHandleExam"-->
              <!--                               :current-page="pageIndexExam" :page-sizes="[10, 20, 50, 100]" :page-size="pageSizeExam" :total="totalPageExam"-->
              <!--                               layout="total, sizes, prev, pager, next, jumper">-->
              <!--                </el-pagination>-->
            </div>
          </div>
        </div>
      </div>

    </el-drawer>
    <div class="mod-user">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">

        <el-form-item label="订单编号:">
          <el-input class="selectWidth" v-model="dataForm.channelOrderNo" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户姓名:">
          <el-input class="selectWidth" v-model="dataForm.userName" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户电话:">
          <el-input class="selectWidth" v-model="dataForm.userPhone" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item label="支付方式:">
          <el-select class="selectWidth" v-model="dataForm.paymentType" placeholder="">
            <el-option
              v-for="item in optionsFangshi"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态:">
          <el-select class="selectWidth" v-model="dataForm.paymentStatus" placeholder="">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="商品类型:">
          <el-select class="selectWidth" v-model="dataForm.type" placeholder="课程类型" >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="year" label="课程年度:">
          <el-date-picker
            v-model="dataForm.year"
            type="year"
            value-format="yyyy"
            placeholder="">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="下单日期">
          <el-date-picker
            v-model="orderDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>


        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
          <el-button @click="exportDataList()">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="orderListTableRef"
        :data="dataList" :height="height"
        border
        :summary-method="getSummaries"
        show-summary
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">

        <el-table-column
          prop="channelOrderNo"
          header-align="center"
          align="center"
          label="编号">
        </el-table-column>
        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          label="客户">
          <template slot-scope="scope">
            <div class="flex-column height-20 ">
              <div>
                {{ scope.row.userName }}
              </div>
              <div> {{ scope.row.userPhone }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="classOrderItemList"
          header-align="center"
          align="center"
          width="350px"
          label="产品">
          <template slot-scope="scope">
            <div class="background-color-white flex-column border-radius"
                 v-for="(item, index) in scope.row.classOrderItemList.length>3?scope.row.classOrderItemList.slice(0, 3):scope.row.classOrderItemList">
              <div class="flex height-20 align-center justify-between">
                <div>
                  {{ item.manageName }}
                </div>
                <div>×{{ item.number }}</div>
              </div>
            </div>
            <div style="color: #999;" v-if="scope.row.classOrderItemList.length>3"> --
              剩余{{scope.row.classOrderItemList.length-3}}项，请在详情中查看 --
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderAmount"
          header-align="center"
          align="center"
          label="金额">
        </el-table-column>
        <el-table-column
          prop="paymentType"
          header-align="center"
          align="center"
          label="支付方式">
          <template slot-scope="scope">
            <span v-if="scope.row.paymentType === 0">微信支付</span>
            <span v-else-if="scope.row.paymentType === 1">支付宝支付</span>
            <span v-else-if="scope.row.paymentType === 3">线下转账</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="paymentTime"
          header-align="center"
          align="center"
          label="支付时间">
        </el-table-column>

        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          label="状态">
          <template slot-scope="scope">
            <span>{{ transformPaymentStatus(scope.row.paymentStatus,scope.row.returnTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">查看</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            <el-button type="text" size="small" v-if="scope.row.paymentStatus==2" @click="refundMoney(scope.row.id)">
              退款
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { saveAs } from 'file-saver';
  export default {
    data() {
      return {
        height: 0,
        dataForm: {
          year: '',
          orderCode: '',
          userName: '',
          userPhone: '',
          paymentType: '',
          paymentStatus: ''
        },
        options: [{
          value: '2',
          label: '已支付'
        }, {
          value: '0',
          label: '支付中'
        }, {
          value: '4',
          label: '已退款'
        }],
        typeOptions:[
          {
            value: '',
            label: '请选择'
          },{
            value: 0,
            label: '专业科目'
          }, {
            value: 1,
            label: '公需科目'
          }
        ],
        optionsFangshi: [{
          value: '0',
          label: '微信'
        }, {
          value: '1',
          label: '支付宝'
        }, {
          value: '3',
          label: '线下转账'
        }],
        orderDate: '',
        tableHeaderStyle: {background: '#f5f7fa !important', height: '20px !important', padding: '4px !important'},
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        classOrder: {
          name: ''
        },
        commentList: [
          {
            xuhao: "1",
            paymentTime: "1",
            orderAmount: "2",
            paymentStatus: "3",
            paymentType: "4",
            paymentNo:"",
            orderCode: "5"
          }
        ]
      }
    },
    components: {},
    activated() {
      this.getDataList()
    },
    mounted() {
      console.log(document.body.clientHeight)
      // 至于减去多少，这个要看你的页面高度和你想将滚动轴固定在哪里了，数值可以更换
      this.$nextTick(() => {
        let tableHeight = document.body.clientHeight - 345
        this.height = tableHeight
      })
    },
    methods: {
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index == 0) {
            sums[index] = '合计';
            return;
          }
          if (column.property == 'orderAmount') {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0).toFixed(2); // 保留两位小数
              sums[index] += ' 元'; // 加上单位
            } else {
              sums[index] = 'N/A';
            }
          } else {
            sums[index] = '';
          }
        });
        return sums;
      },
      transformPay(paymentType) {
        if (paymentType == 1) {
          return "支付宝";
        } else if (paymentType == 3) {
          return "线下转账";
        } else {
          return "微信";
        }
      },
      transformPaymentStatus(paymenttStatus,returnTime) {
        //支付状态 0未支付 1支付中 2 已支付 3,退款中 4,已退款
        // if (paymenttStatus == 0) {
        //   return "未支付";
        // } else
          if (paymenttStatus == 0||paymenttStatus == 1) {
          return "支付中";
        } else if (paymenttStatus == 2) {
          return "已支付";
        } else if (paymenttStatus == 3) {
          return "退款中";
        } else if (paymenttStatus == 4) {
          return "已支付/已退款("+returnTime+")";
        }
      },
      handleClose() {
        this.addOrUpdateVisible = false; // 关闭外层 Drawer 时不关闭内层 Drawer
      },
      repairTableByRef(refName) {
        this.$refs[refName].doLayout()
      },
      exportDataList() {
        let searchParams = {
          ...this.dataForm,
          page: this.pageIndex,
          limit: this.pageSize,
          startDate: this.orderDate && this.orderDate.length > 0 ? this.orderDate[0] + " 00:00:00" : "",
          endDate: this.orderDate && this.orderDate.length > 0 ? this.orderDate[1] + " 23:59:59" : "",
        }
        this.$http.exportFile('/class/order/exportList', searchParams)
          .then(async (res) => {
            console.log(res);
            let blob = new Blob([res])
            saveAs(blob, "订单列表.xlsx")
          }).catch(error => {
          console.error('文件导出失败:', error)
        })
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true

        var params = {
          ...this.dataForm,
          page: this.pageIndex,
          limit: this.pageSize,
          startDate: this.orderDate && this.orderDate.length > 0 ? this.orderDate[0] + " 00:00:00" : "",
          endDate: this.orderDate && this.orderDate.length > 0 ? this.orderDate[1] + " 23:59:59" : "",
        }
        this.$http({
          url: this.$http.adornUrl('/class/order/list'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
          this.$nextTick(() => {
            this.$refs.orderListTableRef.doLayout(); // 修复表格布局
          });
          this.repairTableByRef('orderListTableRef')
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        console.log(val)
        this.dataListSelections = val
      },
      deleteHandle(id) {
        var ids = id.split(',');
        this.$confirm(`确定要进行删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/class/order/delete'),
            method: 'post',
            data: this.$http.adornData({
              'ids': ids
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      refundMoney(orderId) {
        this.$prompt('请输入退款原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({value}) => {
          this.$http({
            url: this.$http.adornUrl('/pay/refund/refundOrder'),
            method: 'post',
            data: this.$http.adornData({
              'orderId': orderId,
              'returnDesc': value
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {
        })
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$http({
          url: this.$http.adornUrl(`/class/order/info/${id}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("获取订单详情", data)
            let res = data.classOrder;
            this.classOrder = res;
            if (this.classOrder.classOrderItemList && this.classOrder.classOrderItemList.length > 0) {
              this.classOrder.classOrderItemList.forEach((item1, index1) => {
                //设置子的序号
                item1.xuhao = index1 + 1;
              })
            }
            this.commentList[0].paymentTime = this.classOrder.paymentTime;
            this.commentList[0].orderAmount = this.classOrder.orderAmount;
            this.commentList[0].paymentStatus = this.classOrder.paymentStatus;
            this.commentList[0].paymentType = this.classOrder.paymentType;
            this.commentList[0].orderCode = this.classOrder.orderCode;
            this.commentList[0].paymentNo = this.classOrder.paymentNo;
            this.commentList[0].returnTime = this.classOrder.returnTime;
            this.commentList[0].channelOrderNo = this.classOrder.channelOrderNo;
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      // 删除
      deleteHandle(id) {
        var userIds = id ? [id] : this.dataListSelections.map(item => {
          return item.userId
        })
        this.$confirm(`确定进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/class/study/delete'),
            method: 'post',
            data: this.$http.adornData(userIds, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {
        })
      }
    }
  }
</script>
<style>
  .right-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .container-header {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px
  }
</style>
